var __mapImages = {
    'MARKER': 'commonmarker.png',
    /*'INT_SEAPORT': 'seaport.png',
    'INT_INTERMODAL_CONTAINER_TERMINAL': 'terminal.png',
    'INT_BORDER_POST': 'border.png',
    'INT_DISTRIBUTION_CENTER': 'distributionnode.png',
    'INT_SIMPLE_NODE': 'node.png',
    'INT_ROAD': 'roadnode.png',
    'INT_RAIL': 'railnode.png',
    'INT_INLAND_WATERWAY': 'inlandwaterwaynode.png',
    'INT_COASTAL_SHIPPING': 'coastalnode.png',
    'INT_OVERSEAS_PORT': 'marinenode.png',
    'INT_POPULATION_CENTER': 'populationcenter.png'*/
};


var __mapColors = {
    "MARKER": '#7C4702',
    "CIRCLE": '#AF92A5',
    "POLYLINE": '#00A6E9',
    "RECTANGLE": '#7C4702',
    "POLYGON": '#D0E290',
    /*"INT_ROAD": '#7C4702',
    "INT_RAIL": '#7F7C7C',
    "INT_COASTAL": '#1A6EB2',
    "INT_INLAND_WATERWAY": '#09B771',
    "INT_MARINE_SHIPPING": '#42BF1C'*/
};

define([
    'views/baseView',
    'models/map/mapManager',
    'models/crud/projectModel',
    'views/map/mapViewUtils',

    'libs/leaflet/InputBox',
    'libs/leaflet/leaflet.draw',
    'libs/leaflet/leaflet.label',
    'libs/leaflet/Google',

    'views/map/controls/L.Control.InfoBar',
    'views/map/controls/exportControl',
    'views/map/controls/generalInfo',
    'views/map/controls/searchBar',
    'views/map/controls/buttonsBar',
    'views/map/controls/toolsBar',
    'views/map/controls/objectCounter',
    'text!templates/map/infoPopup.html',
], function (BaseView,
    MapModel,
    ProjectModel,
    MapViewUtils,
    _Inputbox,
    _LeafletDraw,
    _LeafletLabel,
    _GoogleMap,
    InfoBar,
    ExportControl,
    GeneralInfo,
    SearchBar,
    ButtonsBar,
    ToolsBar,
    ObjectCounter,
    HTMLInfoPopup
    ) {

    var view = BaseView.extend({
        //ver
        el: $("#main-content"),

        map: undefined,
        mapElement: undefined,
        mapViewUtils: undefined,

        workLayer: undefined,
        auxLayer: undefined,
        layerGroup: undefined,
        layerControl: undefined,
        mode: "",
        currentShape: undefined,
        currentSelectedObject: undefined,
        selectedObjectToAdd: undefined,
        shapeDic: {},
        hasChanges: false,
        deletedShapes: [],
        //deletedMarkers: [],

        tools_showDistance: false,
        tools_showInfo: false,
        tools_showLabels: false,
        currentOverStyle: undefined,
        currentOpenFormData: undefined,
        currentLayersWithData: undefined,
        persistMode: false,

        shapesContextMenuItems: undefined,
        extraContextMenuItems: undefined,

        generalInfoControl: undefined,
        searchControl: undefined,
        buttonsControl: undefined,
        toolsControl: undefined,
        //toggleControl: undefined,
        objectCounterControl: undefined,
        giView: undefined,
        bbView: undefined,
        tbView: undefined,
        counterView: undefined,
        mapImages: __mapImages, // VER
        render: function (mapElement) {
            //clearContent($("#main-content"));

            this.mapElement = mapElement;
            this.mapViewUtils = new MapViewUtils();

            var that = this;


            this.shapesContextMenuItems = [{
                text: translate('_polyline'),
                //iconCls: 'icon-road',
                iconCls: 'glyphicon glyphicon-resize-horizontal',
                //callback: function () { that.menuExtraLayerClick("add_road") }
                callback: function () { that.menuExtraLayerClick("add_rectangle") }
            }, {
                text: translate('_polygon'),
                //iconCls: 'icon-pause',
                iconCls: 'glyphicon glyphicon-unchecked',
                //callback: function () { that.menuExtraLayerClick("add_rail") }
                callback: function () { that.menuExtraLayerClick("add_polygon") }
            }, {
                text: translate('_rectangle'),
                //iconCls: 'glyphicon-boat',
                iconCls: 'fa fa-square-o',
                //callback: function () { that.menuExtraLayerClick("add_coastalroute") }
                callback: function () { that.menuExtraLayerClick("add_rectangle") }
            }, {
                text: translate('_circle'),
                //iconCls: 'glyphicon-anchor',
                iconCls: 'fa fa-circle-o',
                //callback: function () { that.menuExtraLayerClick("add_inlandroute") }
                callback: function () { that.menuExtraLayerClick("add_circle") }
            }, {
                text: translate('_marker'),
                //iconCls: 'glyphicon-fishes',
                iconCls: 'glyphicon glyphicon-map-marker',
                //callback: function () { that.menuExtraLayerClick("add_marineroute") }
                callback: function () { that.menuExtraLayerClick("add_marker") }
            }];


            this.extraContextMenuItems = [{
                text: translate('tooltip_seaport_node'),
                icon: 'img/map/buttons/seaport.png',
                callback: function () { that.menuExtraLayerClick("INT_SEAPORT") }
            }, {
                text: translate('tooltip_ict_node'),
                icon: 'img/map/buttons/terminal.png',
                callback: function () { that.menuExtraLayerClick("INT_INTERMODAL_CONTAINER_TERMINAL") }
            }, {
                text: translate('tooltip_border_node'),
                icon: 'img/map/buttons/border.png',
                callback: function () { that.menuExtraLayerClick("INT_BORDER_POST") }
            }, {
                text: translate('tooltip_distribution_node'),
                icon: 'img/map/buttons/distributionnode.png',
                callback: function () { that.menuExtraLayerClick("INT_DISTRIBUTION_CENTER") }
            }, {
                text: translate('tooltip_simple_node'),
                icon: 'img/map/buttons/node.png',
                callback: function () { that.menuExtraLayerClick("INT_SIMPLE_NODE") }
            }, {
                text: translate('tooltip_road_node'),
                icon: 'img/map/buttons/roadnode.png',
                callback: function () { that.menuExtraLayerClick("INT_ROAD") }
            }, {
                text: translate('tooltip_rail_node'),
                icon: 'img/map/buttons/railnode.png',
                callback: function () { that.menuExtraLayerClick("INT_RAIL") }
            }, {
                text: translate('tooltip_inland_node'),
                icon: 'img/map/buttons/inlandwaterwaynode.png',
                callback: function () { that.menuExtraLayerClick("INT_INLAND_WATERWAY") }
            }, {
                text: translate('tooltip_coastal_node'),
                icon: 'img/map/buttons/coastalnode.png',
                callback: function () { that.menuExtraLayerClick("INT_COASTAL_SHIPPING") }
            }, {
                text: translate('tooltip_overseas_node'),
                icon: 'img/map/buttons/marinenode.png',
                callback: function () { that.menuExtraLayerClick("INT_OVERSEAS_PORT") }
            }, {
                text: translate('tooltip_population_center'),
                icon: 'img/map/buttons/populationcenter.png',
                callback: function () { that.menuExtraLayerClick("INT_POPULATION_CENTER") }
            }];

            // create basemaps
            var mapLayer = new L.TileLayer("http://{s}.mqcdn.com/tiles/1.0.0/osm/{z}/{x}/{y}.png", {
                maxZoom: 18,
                subdomains: ["otile1", "otile2", "otile3", "otile4"],
                attribution: ''
            });
            var minimal = L.tileLayer('http://{s}.tile.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/{styleId}/256/{z}/{x}/{y}.png', {
                styleId: 22677,
                attribution: ''
            });
            var midnight = L.tileLayer('http://{s}.tile.cloudmade.com/8ee2a50541944fb9bcedded5165f09d9/{styleId}/256/{z}/{x}/{y}.png', {
                styleId: 997,
                attribution: ''
            });
            var osm = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', {
                maxZoom: 18,
                styleId: 997,
                attribution: ''
            });
            var ggl = new L.Google("ROADMAP");
            var ggl2 = new L.Google("SATELLITE");
            var ggl3 = new L.Google("HYBRID");
            // end basemaps


            this.map = new L.Map(mapElement, {
                center: new L.LatLng(38.004448, -96.359711),
                zoom: 5,
                measureControl: true,
                layers: [osm],
                contextmenu: true,
                attributionControl: false
            });

            this.layerGroup = L.layerGroup().addTo(this.map);

            this.layerControl = L.control.layers({
                "MapQuest OSM": mapLayer,
                "Cloudmade Fresh OSM": midnight,
                "Cloudmade Minimal OSM": minimal,
                "Open Street Map": osm,
                "Google roadmap": ggl,
                "Google satellite": ggl2,
                "Google hybrid": ggl3
            }).addTo(this.map);

            //add workLayer
            this.workLayer = new L.FeatureGroup();
            this.map.addLayer(this.workLayer);
            this.layerControl.addOverlay(this.workLayer, "Work Layer");

            //map events
            this.map.on('click', that.mapClick, this);
            this.workLayer.on('click', that.layerClick, this);
            this.workLayer.on("mouseover", that.mouseOnLayer, this);
            this.workLayer.on("mouseout", that.mouseOutLayer, this);

            // trigger on create new line with draw tool
            this.map.on('draw:created', function (e) {
                that.workLayer.addLayer(e.layer);
                that.validateIntegrity(true);
                that.refreshObjectCount();
                that.changeModeOn();

                //e.layer.bindLabel('', {
                //    direction: 'right',
                //    noHide: true,
                //});
                ////marker.on('dragstart', this.markerDragStart, this);
                ////marker.on('drag', this.markerDrag, this);

                ////if (entityId == undefined && !skipShowInputName)
                //that.showInputName(e.layer._leaflet_id);

                //// agregue esta linea para que cambie de modo al terminar de crear una figura, ver si funciona
                ////that.currentShape.disable();
                //that.mapSetMode("free");
                $("#projectMap").trigger("resetMode");
            });

            // context menu events
            this.map.on('contextmenu.show', function (e) {
                //if (!that.currentSelectedObject && $("#FastPathProjectDetail").length==0)
                //   e.contextmenu.hide();
            });
            this.map.on('contextmenu.hide', function (e) {
                that.map.contextmenu.removeAllItems();
                that.currentSelectedObject = null;
            });

            //aux layer // Para seleccionar elementos del mapa y mantenerlos en la auxLayer
            this.auxLayer = new L.FeatureGroup();
            this.map.addLayer(this.auxLayer);
            this.auxLayer.on('click', that.auxLayerClick, this);

            this.registerEvents(mapElement);
            this.addDefaultControls();
        },
        removeView: function () {

            this.map.remove();
            this.mapViewUtils = null;
            this.workLayer = null;
            this.auxLayer = null;
            this.layerGroup = null;
            this.layerControl = null;
            this.currentShape = null;
            this.currentSelectedObject = null;
            this.selectedObjectToAdd = null;
            this.shapeDic = null;
            this.deletedShapes = null;
            //this.deletedMarkers = null;
            this.currentOverStyle = null;
            this.currentOpenFormData = null;
            this.currentLayersWithData = null;
            this.shapesContextMenuItems = null;
            this.extraContextMenuItems = null;
            this.generalInfoControl = null;
            this.searchControl = null;
            this.buttonsControl = null;
            this.toolsControl = null;
            this.objectCounterControl = null;
            if (this.giView) {
                this.giView.removeView();
            }
            this.giView = null;
            this.bbView = null;
            this.tbView = null;
            this.counterView = null;
            this.mapImages = null;

            $("#projectMap").off()
            $("#projectMap").empty();

        },
        //add control to map
        addControl: function (control) {
            this.map.addControl(control);
        },
        disableMap: function () {
            if (this.map) {
                this.mapViewUtils.disableMap(this.map);
                this.mode = "";
                this.map.getContainer().style.cursor = "";
                this.hideControls();
            }
        },
        enableMap: function () {
            if (this.map) {
                this.mapViewUtils.enableMap(this.map);
                this.showControls();
            }
        },
        // remove all vector from map and data for controls
        clearMap: function () {
            this.clearLayerControl();
            if (this.layerGroup != undefined)
                this.layerGroup.clearLayers();
            if (this.workLayer != undefined)
                this.workLayer.clearLayers();
            this.mode = "";
            this.map.getContainer().style.cursor = "";
            this.refreshObjectCount();
            this.giView.clearContent();
        },
        hideControls: function () {
            $("#projectMap .leaflet-control-container").hide();
        },
        showControls: function () {
            $("#projectMap .leaflet-control-container").show();
        },
        addDefaultControls: function () {
            var that = this;

            // Object Counter Control
            //this.objectCounterControl = L.control.infobar({
            //    position: 'bottomright',
            //    className: 'object-counter'
            //});
            //this.counterView = new ObjectCounter();
            //this.counterView.setElement($(this.objectCounterControl.getContainer()));
            //this.map.addControl(this.objectCounterControl);
            //this.counterView.render();


            //ExportControl
            var exportControl = new ExportControl();
            exportControl.render(this.map, this.workLayer);



            // general info
            this.generalInfoControl = L.control.infobar({
                //position: 'right'
                position: 'left'
            });
            this.giView = new GeneralInfo();
            this.giView.setElement($(this.generalInfoControl.getContainer()));
            this.map.addControl(this.generalInfoControl);
            this.generalInfoControl.hide();
            this.giView.render();


            // search bar
            this.searchControl = L.control.infobar({
                position: 'left',
                className: 'searchbar'
            });
            var sbView = new SearchBar();
            sbView.setElement($(this.searchControl.getContainer()));
            this.map.addControl(this.searchControl);
            sbView.render();


            // tools bar
            this.toolsControl = L.control.infobar({
                position: 'left',
                className: 'toolbar'
            });
            this.tbView = new ToolsBar();
            this.tbView.setElement($(this.toolsControl.getContainer()));
            this.map.addControl(this.toolsControl);
            this.tbView.render();

            // Toogle Edit / Result
            //var exportControl = new ExportControl();
            //exportControl.render(this.map, this.workLayer);

            //this.toggleControl = L.control.infobar({
            //    position: 'left',
            //    className: 'toolbar'
            //});
            //this.tbView = new ToolsBar();
            //this.tbView.setElement($(this.toolsControl.getContainer()));
            //this.map.addControl(this.toolsControl);
            //this.tbView.render();

        },
        // add all controls for build
        addControlsForBuild: function () {


            this.generalInfoControl.show();


            // buttons bar
            this.buttonsControl = L.control.infobar({
                //position: 'right',
                position: 'left',
                className: 'buttonbar'
            });
            this.bbView = new ButtonsBar();
            this.bbView.setElement($(this.buttonsControl.getContainer()));
            this.map.addControl(this.buttonsControl);
            this.bbView.render();

            this.validateIntegrity(true);
            this.changeModeOff();

            $("#" + this.mapElement).addClass("editing");
        },
        // remove all controls added for build
        removeControlsForBuild: function () {
            if (this.map && this.generalInfoControl) {
                this.generalInfoControl.hide();
                this.map.removeControl(this.buttonsControl);
                this.buttonsControl = undefined;
                this.bbView = undefined;
                this.hideControls();
            }

            $("#" + this.mapElement).removeClass("editing");
        },
        //  remove extra layers from layercontrol
        clearLayerControl: function () {

            if (this.layerControl != undefined && this.layerGroup != undefined) {
                var arr = this.layerGroup.getLayers();
                for (var nn = 0; nn < arr.length; nn++) {
                    this.layerControl.removeLayer(arr[nn]);
                }
            }

        },
        // register evens for actiosn on map
        registerEvents: function (mapElement) {
            // MAP EVENTS
            var that = this;
            $("#" + mapElement).on("removeControlsForBuild", function () {
                that.removeControlsForBuild();
            });
            $("#" + mapElement).on("addControlsForBuild", function () {
                that.enableMap();
                that.addControlsForBuild();
            });

            $("#" + mapElement).on("setMode", function (evt, mode, cursor) {
                that.mapSetMode(mode, cursor);
            });

            $("#" + mapElement).on("setTool", function (evt, util, onoff) {
                that.mapSetTool(util, onoff);
            });

            $("#" + mapElement).on("addKMLLayer", function (evt, layerName, layerUrl, noSaveLib) {


                var onLoadKML = function (e) {
                    // create layerlibrary
                    if (!noSaveLib) {
                        var xmlData = new XMLSerializer().serializeToString(e.target._xml);
                        var mapModel = new MapModel();
                        mapModel.createLayerLibrary(layerName, xmlData);
                    }
                };

                var newLayer = that.mapViewUtils.addKMLLayer(that.map, that.layerGroup, layerName, layerUrl, onLoadKML);
                that.layerControl.addOverlay(newLayer, layerName);

                // add events to new layers

                // click on layer
                newLayer.on("click", function (e) {
                    that.extraLayerClick(e);
                });

                // change color on mouse over
                var currentOverStyle;
                newLayer.on("mouseover", function (e) {
                    if (that.mode != "select")
                        return;

                    if (!currentOverStyle && e.layer.options.color)
                        currentOverStyle = e.layer.options.color;

                    if (e.layer.setStyle != undefined) {
                        e.layer.setStyle({ "color": "#149911" });
                    }
                });
                newLayer.on("mouseout", function (e) {
                    if (that.mode != "select")
                        return;

                    if (e.layer.setStyle != undefined) {
                        e.layer.setStyle({ "color": currentOverStyle });
                        currentOverStyle = null;
                    }
                });

            });

            $("#" + mapElement).on("geoSearch", function (evt, address) {
                that.mapViewUtils.moveToLocation(that.map, address, that);
            });

            $("#" + mapElement).on("moveMapTo", function (evt, lat, lan) {
                that.map.panTo(L.latLng(lat, lan));
            });

            $("#" + mapElement).on("showAlertMessage", function (evt, lat, lan, message) {
                that.showIntegrityErrorMessage(L.latLng(lat, lan), message);
            });

            $("#" + mapElement).on("drawAuxLayers", function (evt, layers) {
                that.addLayersToAux(layers);
            });

            $("#" + mapElement).on("showLayers", function (evt, layers) {
                that.showLayers(layers);
            });
            $("#" + mapElement).on("hideLayers", function (evt, layers) {
                that.hideLayers(layers);
            });

            $("#" + mapElement).on("showLayerByType", function (evt, geoType, dataType) {
                that.showLayerByType(geoType, dataType);
            });


            $("#" + mapElement).on("clearAuxLayer", function (evt) {
                that.auxLayer.clearLayers();
            });

            $("#" + mapElement).on("showLinksOrNode", function (evt, id) {

                if (that.mode != "selectLinks") {
                    var layer = that.workLayer.getLayer(id);
                    if (layer) {
                        var arr = [layer._leaflet_id];
                        that.addLayersToAux(arr);
                    }
                }


            });

            $("#" + mapElement).on("resetMode", function (evt) {
                that.mapSetMode("free");
                that.updateModeView();
            });


            $("#" + mapElement).on("changeModeOn", function (evt) {
                that.changeModeOn();
            });


            $("#" + mapElement).on("getLayerDistance", function (evt, entityId, callback) {
                var distance = 0;

                var layer = that.getLayerByEntityId(entityId, "link");
                if (layer) {
                    distance = that.mapViewUtils.getDistanceInMeters(layer.getLatLngs());
                }

                callback(distance);
            });

            $("#" + mapElement).on("validateIntegrity", function (evt) {
                that.validateIntegrity(true);
            });

            $("#" + mapElement).on("showLayerPopup", function (evt, entityId, geoType) {
                // TO DO: VER ESTO
                var layer = that.getLayerByEntityId(entityId, geoType == "1" ? "node" : "link");
                if (layer) {
                    that.showLayerPopup(layer);
                }
                else {
                    showMessage("info", translate("save_changes_then_put_info"));
                }
            });


            $("#" + mapElement).on("isOkToBack", function (evt, callback) {
                // TO DO :Check for changes
                if (that.hasChanges) {

                    if (that.isValid()) {

                        require(['controllers/common/showModal'], function (Controller) {
                            (new Controller()).show(
                                {
                                    title: translate("save_changes"),
                                    text: translate("sure_save_changes"),
                                    buttons: [
                                        { "title": translate("yes"), "css": "primary", "code": "yes" },
                                        { "title": translate("no"), "code": "no" },
                                        { "title": translate("cancel"), "code": "cancel" }
                                    ],
                                    callback: function (code) {
                                        if (code == "yes") {
                                            // dispatch save
                                            $("#projectMapSidebar").trigger("saveProject");
                                            setTimeout(function () {
                                                callback(true);
                                            }, 1000);
                                        } else if (code == "no") {
                                            //$("#projectMapSidebar").trigger("getGeoData");
                                            callback(true);
                                        } else if (code == "cancel") {
                                            // nothing
                                        }
                                    }
                                });
                        });

                    }
                }
                else
                    callback(true);

            });


            $("#" + mapElement).on("setPersistMode", function (evt) {
                that.persistMode = true;
            });



        },
        // return options by Shape
        getShapeOptionsByType: function (mode, className) {
            var options = {
                repeatMode: false,
                shapeOptions: {}
            };
            switch (mode || className) {
                case "POLYLINE":
                case "add_polyline":
                    options.shapeOptions = {
                        color: __mapColors['POLYLINE'],
                        _color: __mapColors['POLYLINE'],
                        weight: 6,
                        clickable: true,
                        attributes: [],
                        className: 'POLYLINE'
                    };
                    break;
                case "RECTANGLE":
                case "add_rectangle":
                    options.shapeOptions = {
                        color: __mapColors['RECTANGLE'],
                        _color: __mapColors['RECTANGLE'],
                        weight: 6,
                        clickable: true,
                        attributes: [],
                        className: 'RECTANGLE'
                    };
                    break;
                case "POLYGON":
                case "add_polygon":
                    options.shapeOptions = {
                        color: __mapColors['POLYGON'],
                        _color: __mapColors['POLYGON'],
                        weight: 6,
                        clickable: true,
                        attributes: [],
                        className: 'POLYGON'
                    };
                    break;
                case "CIRCLE":
                case "add_circle":
                    options.shapeOptions = {
                        color: __mapColors['CIRCLE'],
                        _color: __mapColors['CIRCLE'],
                        weight: 6,
                        clickable: true,
                        attributes: [],
                        className: 'CIRCLE'
                    };
                    break;
            }

            options.shapeOptions.isDirty = true;

            return options;
        },
        changeModeOn: function () {
            this.hasChanges = true;
            this.giView.updateHasChanges(this.hasChanges);
        },
        changeModeOff: function () {
            this.hasChanges = false;
            this.giView.updateHasChanges(this.hasChanges);
        },
        mapSetMode: function (mode, cursor) {

            this.auxLayer.clearLayers();
            this.mapViewUtils.editMode(false, this.workLayer, this);
            this.persistMode = false;
            this.tools_showInfo = false;
            if (this.tbView)
                this.tbView.updateTools(this.tools_showDistance, this.tools_showInfo, this.tools_showLabels);

            // cancel current shape
            if (this.currentShape != undefined) {
                this.currentShape.disable();
                this.currentShape = undefined;
            }
            if (this.giView)
                this.giView.updateMode(mode);


            this.mode = mode;
            switch (mode) {
                case "result":
                    
                    break;
                case "free":
                    break;
                case "select":
                    break;
                case "edit":
                    this.mapViewUtils.editMode(true, this.workLayer, this);
                    break;
                case "join":
                    this.mapViewUtils.clearUnionLayers();
                    break;
                case "magic_route":
                    this.mapViewUtils.clearMagicRoute();
                    break;
                case "selectLinks":
                    this.updateModeView();
                    break;

                    // map mode for Shapes
                case "add_polyline":
                    var options = this.getShapeOptionsByType(mode);
                    this.currentShape = new L.Draw.Polyline(this.map, options);
                    this.currentShape.enable();
                    break;
                case "add_polygon":
                    var options = this.getShapeOptionsByType(mode);
                    this.currentShape = new L.Draw.Polygon(this.map, options);
                    this.currentShape.enable();
                    break;
                case "add_rectangle":
                    var options = this.getShapeOptionsByType(mode);
                    this.currentShape = new L.Draw.Rectangle(this.map, options);
                    this.currentShape.enable();
                    break;
                case "add_circle":
                    var options = this.getShapeOptionsByType(mode);
                    this.currentShape = new L.Draw.Circle(this.map, options);
                    this.currentShape.enable();
                    break;
            }

            if (cursor != undefined) {
                this.map.getContainer().style.cursor = cursor;
            }
        },
        //handle set utils (tools of map)
        mapSetTool: function (util, onoff) {

            switch (util) {
                case "ruller":
                    this.tools_showDistance = (onoff == 1);
                    break;
                case "labels":
                    this.tools_showLabels = (onoff == 1);
                    this.showHideMarkerLabels();
                    break;
                case "info":
                    if (onoff == 1) {
                        this.mapSetMode("free");
                        this.updateModeView();
                    }
                    this.tools_showInfo = (onoff == 1);
                    if (this.tbView)
                        this.tbView.updateTools(this.tools_showDistance, this.tools_showInfo, this.tools_showLabels);
                    break;
            }
        },
        // handle click on map (markers)
        mapClick: function (e) {
            // TO DO: crear nuevas funciones como add_marker pero para el resto?
            //addMarker: function (latlng, options, className, entityId, skipShowInputName) {
            var change = true;
            switch (this.mode) {


                case "add_marker":
                    this.addMarker(e.latlng, undefined, 'MARKER');
                    break;
                //case "add_text":
                //    this.addMarker(e.latlng, undefined, 'TEXT');
                //    break;
                //case "add_table":
                //    this.addMarker(e.latlng, undefined, 'TABLE');
                //    break;
                //case "add_list":
                //    this.addMarker(e.latlng, undefined, 'LIST');
                //    break;
                //case "add_image":
                //    this.addMarker(e.latlng, undefined, 'IMAGE');
                //    break;

                case "magic_route":
                    var that = this;
                    this.mapViewUtils.drawMagicRoute(this.map, this.workLayer, e.latlng, false, function () {
                        that.validateIntegrity(true);
                    });

                    break;

                default:
                    change = false;
                    break;
            }

            if (change) {
                this.changeModeOn();
            }
        },
        // handle click on layers
        layerClick: function (e) {
            if (e.layer != undefined) {

                if (this.tools_showInfo) {
                    this.showAttributes(e.layer, e.latlng);
                    return;
                }

                var that = this;

                switch (this.mode) {
                    case "":
                    case "free":

                        this.showLayerPopup(e.layer, e.latlng);
                        break;

                    case "change_type":
                        if (e.layer instanceof L.Marker) {

                            if (e.layer.options.entityId && this.currentLayersWithData && this.currentLayersWithData.nodes) {
                                //check has data
                                if (this.currentLayersWithData.nodes.indexOf(e.layer.options.entityId) >= 0) {
                                    showMessage("error", translate("changetype_error_node_with_data"));
                                }
                                else {
                                    this.showMenuForChangeType(e.layer, e.latlng);
                                }
                            }
                            else {
                                this.showMenuForChangeType(e.layer, e.latlng);
                            }
                        }
                        else {

                            if (e.layer.options.entityId && this.currentLayersWithData && this.currentLayersWithData.nodes) {
                                //check has data
                                if (this.currentLayersWithData.nodes.indexOf(e.layer.options.entityId) >= 0) {
                                    showMessage("error", translate("changetype_error_node_with_data"));
                                }
                                else {
                                    this.showMenuForChangeType(e.layer, e.latlng);
                                }
                            }
                            else {
                                this.showMenuForChangeType(e.layer, e.latlng);
                            }

                        }


                        break;

                    case "selectLinks":
                        if (e.layer instanceof L.Polyline) {

                            if (this.mapViewUtils.validateEnds(e.layer, this.workLayer)) {
                                var geoData = this.generateTempGeoData(e.layer);
                                this.addLayersToAux([e.layer._leaflet_id]);
                                //this.giView.addSelectedLayer(e.layer._leaflet_id, undefined, true, geoData);
                                this.changeModeOn();
                                this.validateIntegrity(true);
                            }
                            else {
                                showMessage("error", translate("error_link_without_node"));
                            }
                        }
                        break;

                    case "join":
                        this.clearOverStyle(e.layer);
                        var newLayer = this.mapViewUtils.unionLayers(this.workLayer, e.layer, this);
                        if (newLayer) {
                            this.addLayersToAux([newLayer._leaflet_id]);
                            this.checkPersistMode();
                        } else {
                            this.addLayersToAux([e.layer._leaflet_id]);
                        }
                        this.validateIntegrity(true);
                        this.refreshObjectCount();
                        this.changeModeOn();
                        break;

                    case "remove":
                        //update giview
                        if (e.layer instanceof L.Marker) {
                            // find links near marker to remove from corridor network
                            this.checkRemoveLinkOfMarker(e.layer);
                            if (e.layer.options.entityId) {
                                //this.deletedMarkers.push(e.layer.options.entityId);
                                this.deletedShapes.push(e.layer.options.entityId);
                            }

                        }
                        else {
                            this.giView.removeLayerFromMap(e.layer._leaflet_id);
                            if (e.layer.options.entityId) {
                                this.deletedShapes.push(e.layer.options.entityId);
                            }
                        }
                        //end update

                        this.workLayer.removeLayer(e.layer);
                        this.validateIntegrity(true);
                        this.refreshObjectCount();
                        this.changeModeOn();
                        this.checkPersistMode();
                        break;

                    case "edit":
                        if (e.layer instanceof L.Marker) {
                            this.showInputName(e.layer._leaflet_id);
                            this.changeModeOn();
                        }
                        else {
                            this.workLayer.eachLayer(function (layer) {
                                if (layer instanceof L.Polyline) {
                                    layer.editing.disable();
                                }
                            });
                            e.layer.editing.enable();
                        }
                        break;

                    case "magic_route":
                        if (e.layer instanceof L.Marker) {
                            this.mapViewUtils.drawMagicRoute(this.map, this.workLayer, e.layer.getLatLng(), true, function () {
                                that.validateIntegrity(true);
                                that.changeModeOn();
                            });
                        }
                        break;



                    case "magnet_node":
                        if (e.layer instanceof L.Marker) {
                            var coords1 = this.mapViewUtils.getNearObjectCoords(e.layer.getLatLng(), this.workLayer, true);
                            e.layer.setLatLng(coords1);
                            e.layer.options.isDirty = true;
                            this.validateIntegrity(true);
                            this.changeModeOn();
                            this.checkPersistMode();
                        }



                        break;
                    case "magnet":
                        if (e.layer instanceof L.Polyline) {
                            if (e.layer.getLatLngs().length > 0) {

                                var coords1 = this.mapViewUtils.getNearObjectCoords(e.layer._latlngs[0], this.workLayer, false);
                                var coords2 = this.mapViewUtils.getNearObjectCoords(e.layer._latlngs[e.layer._latlngs.length - 1], this.workLayer, false);
                                var newArr = e.layer._latlngs;

                                // have 2 points
                                if (coords1 != coords2) {
                                    // check minor distance to first point
                                    var distanceTo1 = e.layer._latlngs[0].distanceTo(coords1);
                                    var distanceTo2 = e.layer._latlngs[0].distanceTo(coords2);

                                    if (distanceTo1 > distanceTo2) {
                                        newArr[0] = L.latLng(coords2.lat, coords2.lng);
                                    }
                                    else {
                                        newArr[0] = L.latLng(coords1.lat, coords1.lng);
                                    }
                                    // check minor distance to last point
                                    distanceTo1 = e.layer._latlngs[e.layer._latlngs.length - 1].distanceTo(coords1);
                                    distanceTo2 = e.layer._latlngs[e.layer._latlngs.length - 1].distanceTo(coords2);
                                    if (distanceTo1 > distanceTo2) {
                                        newArr[newArr.length - 1] = L.latLng(coords2.lat, coords2.lng);
                                    }
                                    else {
                                        newArr[newArr.length - 1] = L.latLng(coords1.lat, coords1.lng);
                                    }
                                }
                                else {
                                    var distanceTo1 = e.layer._latlngs[0].distanceTo(coords1);
                                    var distanceTo2 = e.layer._latlngs[e.layer._latlngs.length - 1].distanceTo(coords1);
                                    if (distanceTo1 < distanceTo2) {
                                        newArr[0] = L.latLng(coords1.lat, coords1.lng);
                                    }
                                    else {
                                        newArr[newArr.length - 1] = L.latLng(coords1.lat, coords1.lng);
                                    }

                                }
                                // set new array of coords
                                e.layer.setLatLngs(newArr);
                                e.layer.options.isDirty = true;

                                this.validateIntegrity(true);
                                this.changeModeOn();
                                this.checkPersistMode();

                            }

                        }
                        break;

                    case "split":
                        if (e.layer.hasOwnProperty("_latlngs")) {
                            var arr = this.mapViewUtils.splitPolyline(this.map, e.layer._latlngs, e.latlng);
                            if (arr != undefined) {

                                this.deletedShapes.push(e.layer.options.entityId);

                                this.clearOverStyle(e.layer);

                                var poly1 = L.polyline(arr[0], e.layer.options);
                                this.workLayer.addLayer(poly1);
                                poly1.options.isDirty = true;
                                poly1.options.entityId = undefined;

                                var poly2 = L.polyline(arr[1], e.layer.options);
                                this.workLayer.addLayer(poly2);
                                //poly2.options.entityId = -1;
                                poly2.options.isDirty = true;
                                poly2.options.entityId = undefined;

                                this.giView.removeLayerFromMap(e.layer._leaflet_id);
                                this.workLayer.removeLayer(e.layer);

                                this.validateIntegrity(true);
                                this.refreshObjectCount();
                                this.changeModeOn();
                                this.checkPersistMode();
                            }
                        }
                        break;

                }




            }
        },
        clearOverStyle: function (layer) {
            if (this.currentOverStyle) {
                layer.setStyle({ "color": this.currentOverStyle });
                this.currentOverStyle = null;
            }
        },
        // manage click on extra layers
        extraLayerClick: function (e) {
            if (e.layer != undefined) {

                var that = this;

                if (this.tools_showInfo) {
                    this.showAttributes(e.layer, e.latlng);
                    return;
                }

                switch (this.mode) {
                    case "select":

                        this.currentSelectedObject = e.layer;
                        this.selectedObjectToAdd = e.layer;
                        if (this.selectedObjectToAdd instanceof L.Polyline) {
                            this.map.contextmenu.removeAllItems();
                            $.each(this.shapesContextMenuItems, function (ii, item) {
                                that.map.contextmenu.addItem(item);
                            });
                            this.map.contextmenu.showAt(e.latlng);
                        } else {
                            this.map.contextmenu.removeAllItems();
                            $.each(this.extraContextMenuItems, function (ii, item) {
                                that.map.contextmenu.addItem(item);
                            });
                            this.map.contextmenu.showAt(e.latlng);
                        }
                        break;

                }
            }
        },
        menuExtraLayerClick: function (mode) {

            if (this.mode == "change_type")
                this.changeLayerType(mode)
            else {
                if (this.selectedObjectToAdd instanceof L.Polyline) {

                    var latLangs = this.selectedObjectToAdd.getLatLngs();
                    var options = this.getShapeOptionsByType(mode);
                    var poly = L.polyline(latLangs, options.shapeOptions);
                    this.workLayer.addLayer(poly);
                    if (this.selectedObjectToAdd.options.attributes) {
                        poly.options.attributes = [];
                        for (var nn = 0; nn < this.selectedObjectToAdd.options.attributes.length; nn++) {
                            poly.options.attributes.push($.extend({}, this.selectedObjectToAdd.options.attributes[nn]));
                        }
                    }
                    this.validateIntegrity(true);
                    this.refreshObjectCount();

                    // copy all points (for best precision)
                    //this.mapViewUtils.simplifyPolyline(this.map,poly, 3);
                }
                if (this.selectedObjectToAdd instanceof L.Marker) {
                    var latLang = this.mapViewUtils.cloneLatLns(this.selectedObjectToAdd.getLatLng());
                    var leafid = this.addMarker(latLang, undefined, mode);

                    if (this.selectedObjectToAdd.options.attributes) {
                        var marker = this.workLayer.getLayer(leafid);
                        marker.options.attributes = [];
                        for (var nn = 0; nn < this.selectedObjectToAdd.options.attributes.length; nn++) {
                            marker.options.attributes.push($.extend({}, this.selectedObjectToAdd.options.attributes[nn]));
                        }
                    }
                }

                this.selectedObjectToAdd = null;
            }


        },
        // Manager click on aux layer
        auxLayerClick: function (e) {
            if (e.layer != undefined) {
                var that = this;
                switch (this.mode) {
                    case "selectLinks":
                        this.giView.removeSelectedLayer(e.layer.refId || e.layer._leaflet_id, true);
                        this.auxLayer.removeLayer(e.layer);
                        this.validateIntegrity(true);

                        break;

                }

            }
        },
        // add marker to work layer
        addMarker: function (latlng, options, className, entityId, skipShowInputName) {
            var icon = this.mapImages[className];

            if (options == undefined && icon != undefined) {
                options = {
                    draggable: false,
                    isDirty: true,
                    zIndexOffset: 10000,
                    alt: 'alt',
                    className: className,
                    attributes: [],
                    icon: L.icon({
                        iconUrl: 'img/map/pins/' + icon,
                        iconSize: [32, 37],
                        iconAnchor: [16, 37],
                        labelAnchor: [8, -18]
                    })
                };
            }
            if (options && entityId) {
                options.entityId = entityId;
                options.isDirty = false;
            }

            if (this.workLayer) {
                var marker = new L.marker(latlng, options).addTo(this.workLayer);
                marker.bindLabel('', {
                    direction: 'right',
                    noHide: true,
                });
                marker.on('dragstart', this.markerDragStart, this);
                marker.on('drag', this.markerDrag, this);

                if (entityId == undefined && !skipShowInputName)
                    this.showInputName(marker._leaflet_id);

                //return marker._leaflet_id;
                return marker;
            }


        },
        /*
        type == "node" && layer instanceof L.Marker || type == "link" && layer instanceof L.Polyline ||
                            type == "link" && layer instanceof L.Circle || type == "link" && layer instanceof L.Rectangle ||
                            type == "link" && layer instanceof L.Polygon)
                            */
        // display distance indicator
        mouseOnLayer: function (e) {
            if (this.tools_showDistance) {
                this.mapViewUtils.displayDistance(e, this.map);
            }

            if (e.layer instanceof L.Marker) {
                if (this.mode == "result" && e.layer.getPopup()) {
                    e.layer.openPopup();
                } else {
                    e.layer.showLabel();
                }
            }

            else if (e.layer instanceof L.Polyline) {
                if (this.mode == "result") {
                    e.layer.openPopup();
                }
            }

            else if (e.layer instanceof L.Circle) {
                if (this.mode == "result") {
                    e.layer.openPopup();
                }
            }

            else if (e.layer instanceof L.Rectangle) {
                if (this.mode == "result") {
                    e.layer.openPopup();
                }
            }

            else if (e.layer instanceof L.Polygon) {
                if (this.mode == "result") {
                    e.layer.openPopup();
                }
            }
            /*
            if (e.layer instanceof L.Marker) { // && e.originalEvent.which == 0) {

                e.layer.showLabel();
                //e.layer.togglePopup();

                if (this.mode != "selectLinks") {

                    // find links to highlight
                    var that = this;
                    var arr = [];
                    this.workLayer.eachLayer(function (layer) {
                        if (layer instanceof L.Polyline) {
                            if (e.layer.getLatLng().distanceTo(layer.getLatLngs()[0]) < 100) {
                                arr.push(layer._leaflet_id);
                            }
                            else {
                                if (e.layer.getLatLng().distanceTo(layer.getLatLngs()[layer.getLatLngs().length - 1]) < 100) {
                                    arr.push(layer._leaflet_id);
                                }
                            }
                        }
                    });

                    this.giView.highlightLinks(arr);
                }
            }

            if (e.layer instanceof L.Polyline) {
                if (!this.currentOverStyle)
                    this.currentOverStyle = e.layer.options.color;
                e.layer.setStyle({ "color": "#149999" });

                if (this.mode != "selectLinks") {
                    this.giView.highlightLinks([e.layer._leaflet_id]);
                }
            }
            */
        },
        // hide distance indicator
        mouseOutLayer: function (e) {
            if (this.tools_showDistance) {
                this.mapViewUtils.hideDistance(e, this.map);
            }
            if (e.layer instanceof L.Marker) {
                if (e.layer.hideLabel && !this.tools_showLabels)
                    e.layer.hideLabel();
            }
            if (e.layer instanceof L.Polyline) {
                if (this.currentOverStyle) {
                    e.layer.setStyle({ "color": this.currentOverStyle });
                    this.currentOverStyle = null;
                }
            }

            if (this.mode != "selectLinks") {
                this.giView.highlightLinks();
            }
        },
        // event on start marker drag
        markerDragStart: function (e) {
            this.mapViewUtils.findLinksToDrag(this.workLayer, e.target.getLatLng())
            e.target.options.isDirty = true;
            $("#" + this.mapElement + " .project_input_shapename").trigger("focusout");

        },
        // event on dragging marker
        markerDrag: function (e) {
            this.mapViewUtils.performDragLinks(this.workLayer, e.target.getLatLng())
        },
        // return mapdata (geodata) in order to save it
        getMapData: function () {

            this.mapSetMode("free");
            this.updateModeView();

            this.changeModeOff();

            var that = this;
            var res = {
                geometries: [],
                deletedShapes: [],
                integrityOk: false,
            };

            this.workLayer.eachLayer(function (layer) {
                
                if (layer.options.isDirty) {
                    var dataType = layer.options.className;

                    var itemGeo = {
                        geometryId: layer._leaflet_id,
                        geometryType: 0,//(isMarker ? 1 : 2), // TO DO:  mas tipos de shapes
                        dataType: dataType,
                        entityId: layer.options.entityId || (-1),
                        name: that.getShapeName(layer._leaflet_id),
                        points: [],
                        attributes: []
                    }

                    switch (dataType.toLowerCase()) {
                        case "marker":
                            if (itemGeo.name == "")
                                itemGeo.name = "Marker";
                            itemGeo.geometryType = 1;
                            itemGeo.pointData = layer.getLatLng().lng + " " + layer.getLatLng().lat;
                            break;
                        case "polyline":
                            // To Do: al terminar de crear la polyline pedir un nombre como los markers
                            itemGeo.geometryType = 2;
                            itemGeo.name = "Polyline"; // ver si hace falta
                            var latlngs = layer.getLatLngs();
                            itemGeo.pointData = "";
                            for (var nn = 0; nn < latlngs.length; nn++) {
                                itemGeo.pointData += "," + latlngs[nn].lng + " " + latlngs[nn].lat;
                            }
                            if (itemGeo.pointData != "") {
                                itemGeo.pointData = itemGeo.pointData.substr(1);
                            }
                            break;
                        case "polygon":
                            // To Do: al terminar de crear el polygon pedir un nombre como los markers
                            itemGeo.geometryType = 3;
                            itemGeo.name = "Polygon";
                            var latlngs = layer.getLatLngs();
                            itemGeo.pointData = "";
                            for (var nn = 0; nn < latlngs.length; nn++) {
                                itemGeo.pointData += "," + latlngs[nn].lng + " " + latlngs[nn].lat;
                            }
                            if (itemGeo.pointData != "") {
                                itemGeo.pointData = itemGeo.pointData.substr(1);
                            }
                            break;
                        case "rectangle":
                            // To Do: al crear el rectangle pedir un nombre como los markers
                            itemGeo.name = "Rectangle";
                            itemGeo.geometryType = 4;
                            var latlngs = layer.getLatLngs();
                            itemGeo.pointData = "";
                            for (var nn = 0; nn < latlngs.length; nn++) {
                                itemGeo.pointData += "," + latlngs[nn].lng + " " + latlngs[nn].lat;
                            }
                            if (itemGeo.pointData != "") {
                                itemGeo.pointData = itemGeo.pointData.substr(1);
                            }
                            break;
                        case "circle":
                            // To Do: al crear el circulo pedir un nombre como los markers
                            itemGeo.name = "Circle";
                            itemGeo.geometryType = 5;
                            itemGeo.pointData = layer.getLatLng().lng + " " + layer.getLatLng().lat;
                            
                            // ACTUALIZAR RADIO DEL CIRCULO
                            var radius = $.grep(layer.options.attributes, function (e) {
                                return e.key === "radius";
                            })[0];
                            if (radius) {
                                radius.value = layer.getRadius();
                            } else {
                                layer.options.attributes.push({ "key": "radius", "type": "radius", "value": layer.getRadius() });
                            }
                            ////itemGeo.attributes.push({ "key": "radius", "type": "radius", "value": layer.getRadius() });
                            //itemGeo.attributes = layer.options.attributes;
                            break;
                        default: // figura no soportada
                            break;
                    }
                    
                    if (layer.options.attributes) {
                        for (var nn = 0; nn < layer.options.attributes.length; nn++) {
                            itemGeo.attributes.push($.extend({}, layer.options.attributes[nn]));
                        }
                    }

                    res.geometries.push(itemGeo);
                }
            });

            //var corridorData = that.giView.getCorridorsData(that.workLayer);
            //res = $.extend(res, corridorData);
            //res.deletedLinks = this.deletedLinks;
            res.deletedShapes = this.deletedShapes;
            //res.deletedNodes = this.deletedNodes;
            //res.deletedMarkers = this.deletedMarkers;

            var errors = this.validateIntegrity(true);
            if (!errors || errors.length == 0) {
                res.integrityOk = true;
            }

            return res;
        },

        // return array of layers data for save
        getLayers: function () {

        },
        // check for nodes without links and links without nodes
        validateIntegrity: function (displayResult) {
            // TO DO: definir el test de integridad segun el tipo de shape

            var that = this;
            var res = [];
            //var tolerance = 100; //tolerance in mts
            //var found = false;
            //var foundEnd;
            //this.workLayer.eachLayer(function (layer) {
            //    var errorItem = undefined;
            //    if (layer instanceof L.Marker) {
            //        found = false;
            //        that.workLayer.eachLayer(function (layer2) {
            //            if (layer != layer2) {
            //                if (layer2 instanceof L.Polyline) {
            //                    if (layer.getLatLng().distanceTo(layer2.getLatLngs()[0]) <= tolerance || layer.getLatLng().distanceTo(layer2.getLatLngs()[layer2.getLatLngs().length - 1]) <= tolerance) {
            //                        found = true;
            //                    }
            //                }
            //            }
            //        });
            //        if (!found) {
            //            errorItem = {
            //                leafletId: layer._leaflet_id,
            //                point: layer.getLatLng(),
            //                error: translate("error_node_without_links").replace("##node##", that.getShapeName(layer._leaflet_id))
            //            }
            //        }

            //    }
            //    else {

            //        found = false;
            //        foundEnd = false;
            //        that.workLayer.eachLayer(function (layer2) {
            //            if (layer != layer2) {
            //                if (layer2 instanceof L.Marker) {
            //                    if (layer2.getLatLng().distanceTo(layer.getLatLngs()[0]) <= tolerance) {
            //                        found = true;
            //                    }
            //                    if (layer2.getLatLng().distanceTo(layer.getLatLngs()[layer.getLatLngs().length - 1]) <= tolerance) {
            //                        foundEnd = true;
            //                    }
            //                }
            //            }
            //        });
            //        if (!found || !foundEnd) {
            //            errorItem = {
            //                leafletId: layer._leaflet_id,
            //                point: (found ? layer.getLatLngs()[layer.getLatLngs().length - 1] : layer.getLatLngs()[0]),
            //                error: translate("error_link_without_node")
            //            }
            //        }
            //        else if (found && foundEnd) {
            //            if (that.giView.getSubcorridorIdFromLayerId(layer._leaflet_id).length == 0) {

            //                var geoData = that.generateTempGeoData(layer);
            //                var name = geoData.link.name;

            //                errorItem = {
            //                    leafletId: layer._leaflet_id,
            //                    point: layer.getLatLngs()[Math.floor(layer.getLatLngs().length / 2)],
            //                    error: translate("error_link_without_subcorridor").replace("#name#", name)
            //                }
            //            }

            //        }

            //    }

            //    if (errorItem) {
            //        res.push(errorItem);
            //    }

            //});

            //if (this.giView && displayResult) {
            //    if (res.length > 0)
            //        this.giView.showIntegrityErrors(res);
            //    else
            //        this.giView.clearIntegrityErrors()
            //}
            //this.giView.updateIntegrityStatus(res.length > 0, this.workLayer.getLayers().length);

            return res;
        },
        showIntegrityErrorMessage: function (latlng, message) {
            // To DO: no lo estoy usando por ahora
            var tooltip = new L.Tooltip(this.map);
            tooltip.updateContent({
                text: message
            });
            tooltip.updatePosition(latlng);
            setTimeout(function () {
                tooltip.dispose();
                tooltip = null;
            }, 3000);

        },
        // show input for node name
        showInputName: function (leafletId) {
            var that = this;
            var text = "";

            var shape = this.workLayer.getLayer(leafletId);

            if (this.getShapeName(leafletId) != "")
                text = this.getShapeName(leafletId);
            else
                text = this.mapViewUtils.countMarkers(this.workLayer);
                //text = "Node " + this.mapViewUtils.countMarkers(this.workLayer);

            var inputBox = new L.InputBox(this.map);
            inputBox.updateContent(text, leafletId, function (id, name) {
                that.addShapeName(id, name);
                if (that.tools_showLabels) {
                    shape.showLabel();
                }
            });
            //if(shape instanceof L.Marker)// || shape instanceof L.Circle){
                inputBox.updatePosition(shape.getLatLng());
                shape.hideLabel();
            //} else if (shape instanceof L.Polygon || shape instanceof L.Rectangle) {
            //    inputBox.updatePosition(shape.getLatLngs()[0]);
            //    //shape.hideLabel();
            //    shape._hideLabel();
            //}
            //shape.hideLabel();
        },
        // add name to shape
        addShapeName: function (id, name) {
            this.setShapeName(id, name);
            var shape = this.workLayer.getLayer(id);
            if (shape) {
                shape.options.title = name;
                shape.options.isDirty = true;
                if(shape instanceof L.Marker){
                    shape.update();
                }else{
                    shape.updateLabelContent();
                }
                this.validateIntegrity(true);
                this.refreshObjectCount();

                //update name on corridor network
                //this.updateGIViewFromMarker(shape);
            }

        },
        updateGIViewFromMarker: function (shape) {
            var that = this;
            this.workLayer.eachLayer(function (layer) {
                if (layer instanceof L.Polyline) {
                    if (shape.getLatLng().distanceTo(layer.getLatLngs()[0]) < 100) {
                        that.giView.updateSelectedLayer(that.generateTempGeoData(layer));
                    }
                    else {
                        if (shape.getLatLng().distanceTo(layer.getLatLngs()[layer.getLatLngs().length - 1]) < 100) {
                            that.giView.updateSelectedLayer(that.generateTempGeoData(layer));
                        }
                    }
                }
            });
        },
        refreshObjectCount: function () {
            // comentado, no voy a usar contador
            //this.counterView.updateObjectCount(this.workLayer);
        },
        addLayersToAux: function (ids) {
            // To Do: ver para que se usa esta fx
            if (!ids)
                return;
            for (var nn = 0; nn < ids.length; nn++) {

                var layer = this.workLayer.getLayer(ids[nn]);
                if (layer) {

                    if (layer instanceof L.Polyline) {
                        var opts = $.extend({}, layer.options);
                        opts.weight = 10;
                        //opts.color = opts._color || opts.color;
                        opts.color = "#fa2222";
                        var poly = L.polyline(layer.getLatLngs(), opts);
                        poly.refId = ids[nn];
                        this.auxLayer.addLayer(poly);
                    }
                    else if (layer instanceof L.Marker) {
                        var opts = $.extend(true, {}, layer.options);
                        if (opts.icon) {

                            opts.icon = L.icon({
                                iconUrl: opts.icon.options.iconUrl,
                                iconSize: [32, 37],
                                iconAnchor: [18, 39]
                            });
                            opts.icon.options.className = "marker-active";

                        }
                        var latlng = this.mapViewUtils.cloneLatLns(layer.getLatLng());
                        var marker = new L.Marker(latlng, opts);
                        this.auxLayer.addLayer(marker);
                    }
                }
            }

        },
        showLayers: function (ids) {
            this.setLayersOpacity(ids, 1, 0.5);
        },
        hideLayers: function (ids) {
            this.setLayersOpacity(ids, 0.1, 0.1);
        },
        setLayersOpacity: function (ids, opacityMarker, opacityPoly) {
            if (!ids)
                return;

            for (var nn = 0; nn < ids.length; nn++) {

                var layer = this.workLayer.getLayer(ids[nn]);
                if (layer) {
                    if (layer instanceof L.Polyline) {
                        layer.setStyle({ opacity: opacityPoly });
                    }
                    else if (layer instanceof L.Marker) {
                        layer.setOpacity(opacityMarker)
                    }
                }
            }

        },
        setMapData: function (geoData, skipClear) {
            // skipClear: para hacer refresh solamente.

            if (!skipClear) {
                this.clearMap();
                this.enableMap();
            }

            //fill corridor with geometries
            //geoData = this.fillGeoData(geoData); //comentado, facu
            var that = this;

            //corridors


            $("#stepInfo").html(translate("loading_corridor_network")).show();
            setTimeout(function () {

                //that.giView.setCorridorData(geoData.corridors, skipClear); // Facu, comentado

                $("#stepInfo").html(translate("loading_links_and_nodes")).show();

                setTimeout(function () {
                    // geometries: Marker = 1, Polyline = 2, Polygon = 3, Rectangle = 4, Circle = 5
                    //add and update
                    $.each(geoData.geometries, function (ii, item) {
                        
                        var attr = [];
                        $.each(item.attributes, function () {
                            attr[this.key] = { type: this.type, value: this.value };
                        })

                        switch (item.geometryType) {
                            case 1: // Marker
                                if (!skipClear || that.deletedShapes.indexOf(item.entityId) == -1) {

                                    var shape;//, geometryId;
                                    if (skipClear) {
                                        shape = that.getLayerByEntityId(item.entityId, "node");
                                    }
                                    var latlng = new L.LatLng(item.points[0].lat, item.points[0].lng);

                                    if (shape) {
                                        //geometryId = shape._leaflet_id;
                                        shape.setLatLng(latlng);
                                    }
                                    else {
                                        shape = that.addMarker(latlng, undefined, item.dataType, item.entityId);
                                    }

                                    that.setShapeName(shape._leaflet_id, item.name);

                                    shape.options.title = item.name;
                                    if (item.attributes && item.attributes.length > 0) {
                                        shape.options.attributes = item.attributes;
                                    }

                                    // Asigna atributos en forma de objeto
                                    shape.options.attrObj = attr;

                                    if (attr.text) {
                                        shape.bindPopup(attr.text.value);
                                    }
                                    

                                    shape.update();
                                }
                                break;
                            case 2: // POLYLINE
                                if (!skipClear || that.deletedShapes.indexOf(item.entityId) == -1) {

                                    var shape;//, geometryId;
                                    if (skipClear) {
                                        shape = that.getLayerByEntityId(item.entityId, "link");
                                    }

                                    if (shape) {
                                        //geometryId = shape._leaflet_id;
                                        shape.setLatLngs(item.points);
                                    }
                                    else {
                                        var options = that.getShapeOptionsByType(undefined, item.dataType);
                                        options.shapeOptions.entityId = item.entityId;
                                        options.shapeOptions.isDirty = false;
                                        shape = L.polyline(item.points, options.shapeOptions);
                                        that.workLayer.addLayer(shape);

                                        //geometryId = shape._leaflet_id;
                                    }

                                    if (item.attributes && item.attributes.length > 0) {
                                        shape.options.attributes = item.attributes;
                                    }
                                    shape.options.title = item.name;

                                    that.setShapeName(shape._leaflet_id, item.name);

                                    // Asigna atributos en forma de objeto
                                    shape.options.attrObj = attr;

                                    if (attr.text) {
                                        shape.bindPopup(attr.text.value);
                                    }
                                    //$.each(item.parentTempIds, function (nn, tempId) {
                                    //    that.giView.addSelectedLayer(shape._leaflet_id, tempId, false, item.entityId);
                                    //});
                                }
                                break;
                            case 3: // POLYGON
                                if (!skipClear || that.deletedShapes.indexOf(item.entityId) == -1) {

                                    var shape;//, geometryId;
                                    if (skipClear) {
                                        shape = that.getLayerByEntityId(item.entityId, "link");
                                    }

                                    if (shape) {
                                        //geometryId = shape._leaflet_id;
                                        shape.setLatLngs(item.points);
                                    }
                                    else {
                                        var options = that.getShapeOptionsByType(undefined, item.dataType);
                                        options.shapeOptions.entityId = item.entityId;
                                        options.shapeOptions.isDirty = false;
                                        shape = L.polygon(item.points, options.shapeOptions);
                                        that.workLayer.addLayer(shape);

                                        //geometryId = shape._leaflet_id;
                                    }

                                    shape.options.title = item.name;
                                    that.setShapeName(shape._leaflet_id, item.name);

                                    if (item.attributes && item.attributes.length > 0) {
                                        shape.options.attributes = item.attributes;
                                    }
                                    // Asigna atributos en forma de objeto
                                    shape.options.attrObj = attr;
                                    //$.each(item.parentTempIds, function (nn, tempId) {
                                    //    that.giView.addSelectedLayer(shape._leaflet_id, tempId, false, item.entityId);
                                    //});
                                    //var polygon = that.workLayer.getLayer(geometryId);
                                    shape.options.title = item.name;
                                    if (item.attributes && item.attributes.length > 0) {
                                        shape.options.attributes = item.attributes;
                                    }

                                    if (attr.text) {
                                        shape.bindPopup(attr.text.value);
                                    }

                                    shape.updateLabelContent();

                                }
                                break;
                            case 4: // Rectangle
                                if (!skipClear || that.deletedShapes.indexOf(item.entityId) == -1) {

                                    var shape;//, geometryId;
                                    if (skipClear) {
                                        shape = that.getLayerByEntityId(item.entityId, "link");
                                    }

                                    if (shape) {
                                        //geometryId = shape._leaflet_id;
                                        shape.setLatLngs(item.points);
                                    }
                                    else {
                                        var options = that.getShapeOptionsByType(undefined, item.dataType);
                                        options.shapeOptions.entityId = item.entityId;
                                        options.shapeOptions.isDirty = false;
                                        shape = L.rectangle(item.points, options.shapeOptions);
                                        that.workLayer.addLayer(shape);

                                        //geometryId = shape._leaflet_id;
                                    }

                                    shape.options.title = item.name;
                                    that.setShapeName(shape._leaflet_id, item.name);

                                    if (item.attributes && item.attributes.length > 0) {
                                        shape.options.attributes = item.attributes;
                                    }

                                    // Asigna atributos en forma de objeto
                                    shape.options.attrObj = attr;
                                    //$.each(item.parentTempIds, function (nn, tempId) {
                                    //    that.giView.addSelectedLayer(shape._leaflet_id, tempId, false, item.entityId);
                                    //});
                                    //var rectangle = that.workLayer.getLayer(geometryId);
                                    shape.options.title = item.name;
                                    if (item.attributes && item.attributes.length > 0) {
                                        shape.options.attributes = item.attributes;
                                    }

                                    if (attr.text) {
                                        shape.bindPopup(attr.text.value);
                                    }

                                    shape.updateLabelContent();

                                }
                                break;
                            case 5: // CIRCLE
                                //var auxRadius = $.grep(item.attributes, function(e){ return e.key === "radius"; })[0];
                                if (attr["radius"] && (!skipClear || that.deletedShapes.indexOf(item.entityId) == -1)) {

                                    var shape;//, geometryId;

                                    if (skipClear) {
                                        shape = that.getLayerByEntityId(item.entityId, "link");
                                    }
                                    var latlng = new L.LatLng(item.points[0].lat, item.points[0].lng);

                                    if (shape) {
                                        //geometryId = shape._leaflet_id;
                                        shape.setLatLng(latlng);

                                        shape.setRadius(+attr["radius"].value);
                                        //shape.setRadius(item.radius);
                                    }
                                    else {

                                        var options = that.getShapeOptionsByType(undefined, item.dataType);
                                        options.shapeOptions.entityId = item.entityId;
                                        options.shapeOptions.isDirty = false;
                                        shape = L.circle(latlng, +attr["radius"].value, options.shapeOptions);
                                        that.workLayer.addLayer(shape);

                                        //geometryId = shape._leaflet_id;
                                    }
                                    if (item.attributes && item.attributes.length > 0) {
                                        shape.options.attributes = item.attributes;
                                    }
                                    shape.options.title = item.name;
                                    that.setShapeName(shape._leaflet_id, item.name);

                                    // Asigna atributos en forma de objeto
                                    shape.options.attrObj = attr;

                                    //$.each(item.parentTempIds, function (nn, tempId) {
                                    //    that.giView.addSelectedLayer(shape._leaflet_id, tempId, false, item.entityId);
                                    //});
                                    //
                                    if (attr.text) {
                                        shape.bindPopup(attr.text.value);
                                    }
                                    //var circle = that.workLayer.getLayer(geometryId);
                                    
                                    shape.updateLabelContent();
                                    //circle.update();
                                }
                                break;
                            
                        }
                    });


                    //delete old exist
                    if (skipClear) {
                        var inGeometries = function (id, geoType) {
                            for (var nn = 0; nn < geoData.geometries.length; nn++) {
                                if (geoData.geometries[nn].geometryType == geoType && geoData.geometries[nn].entityId == id) {
                                    return true;
                                }
                            }
                            return false;
                        }

                        that.workLayer.eachLayer(function (layer) {

                            if (layer.options.entityId) {

                                if (layer instanceof L.Polyline) {
                                    // link
                                    if (!inGeometries(layer.options.entityId, 2)) {
                                        that.giView.removeLayerFromMap(layer._leaflet_id);
                                        that.workLayer.removeLayer(layer);
                                    }
                                }
                                else {
                                    //node
                                    if (!inGeometries(layer.options.entityId, 1)) {
                                        that.checkRemoveLinkOfMarker(layer);
                                        that.workLayer.removeLayer(layer);
                                    }
                                }
                            }
                        });

                    }


                    that.validateIntegrity(true);
                    // comentado, no voy a usar contador
                    //that.refreshObjectCount();
                    if (!skipClear) {
                        if (that.workLayer.getBounds().isValid()) {
                            that.map.fitBounds(that.workLayer.getBounds(), { paddingTopLeft: [550, 0] });
                        }
                    }

                    $("#stepInfo").hide();

                    // mark nodes/links with data
                    // comentado el evento
                    //$("#projectMapSidebar").trigger("markWithData");
                });
            });
        },
        // fill and format geoData to show links and nodes in template
        // NO LO UTILIZARE
        // Completa los extremos de cada link, asociando nodos
        fillGeoData: function (geoData) {

            var scDic = {};
            
            for (var nn = 0; nn < geoData.geometries.length; nn++) {
                if (geoData.geometries[nn].geometryType == 2) { //links
                    for (var ll = 0; ll < geoData.geometries[nn].parentTempIds.length; ll++) {
                        //var key = geoData.geometries[nn].parentTempIds[ll];
                        if (!scDic[key])
                            scDic[key] = [];

                        //find nodes (from/to)
                        var nodeFrom;
                        var nodeTo;
                        if (geoData.geometries[nn].extra1 || geoData.geometries[nn].extra2) {
                            for (var jj = 0; jj < geoData.geometries.length; jj++) {
                                if (geoData.geometries[jj].geometryType == 1) {

                                    if (geoData.geometries[nn].extra1 == geoData.geometries[jj].entityId) {
                                        nodeFrom = geoData.geometries[jj];
                                        nodeFrom.img = 'img/map/pins/' + __mapImages[geoData.geometries[jj].dataType];
                                    }
                                    else if (geoData.geometries[nn].extra2 == geoData.geometries[jj].entityId) {
                                        nodeTo = geoData.geometries[jj];
                                        nodeTo.img = 'img/map/pins/' + __mapImages[geoData.geometries[jj].dataType];
                                    }
                                }
                            }
                        }
                        scDic[key].push({
                            link: geoData.geometries[nn],
                            linkColor: __mapColors[geoData.geometries[nn].dataType] || "#dd0000",
                            nodeFrom: nodeFrom,
                            nodeTo: nodeTo,
                        })
                    }
                }
            }

            return geoData;
        },
        // update id's generated in save
        updateMapData: function (data) {
            if (data) {
                var that = this;
                //Update geometries
                $.each(data.geometries, function (ii, item) {
                    var mapItem = that.workLayer.getLayer(item.geometryId);
                    if (mapItem) {
                        mapItem.options.entityId = item.entityId;
                        mapItem.options.isDirty = false;
                    }
                });

                // update corridors and subcorridors
                //this.giView.updateCorridorData(data);

                // comentado el evento
                //$("#projectMapSidebar").trigger("markWithData");

                this.deletedShapes = [];
                //this.deletedMarkers = [];

            }
        },
        getLayerByEntityId: function (entityId, type) {
            // TO DO: actualizar esta funcion con los diferentes shapes
            // ver llamadas a esta fx despues de actualizarla
            var res;
            if (this.workLayer) {
                this.workLayer.eachLayer(function (layer) {
                    if (layer.options && layer.options.entityId == entityId) {
                        if (type == "node" && layer instanceof L.Marker || type == "link" && layer instanceof L.Polyline ||
                            type == "link" && layer instanceof L.Circle || type == "link" && layer instanceof L.Rectangle ||
                            type == "link" && layer instanceof L.Polygon)
                            res = layer;
                    }
                });
            }
            return res;

        },
        setShapeName: function (id, name) {
            this.shapeDic[id] = name;
            var layer = this.workLayer.getLayer(id);
            if (layer) {
                layer.updateLabelContent(name);
            }

        },
        getShapeName: function (id) {
            return this.shapeDic[id] || "";
        },
        isValid: function () {
            var res = true;

            return res;
        },
        // show popup with layer attributes
        showAttributes: function (layer, latlng) {
            // TO DO: Mejorar este metodo para que devuelva mas info????
            if (layer && layer.options && layer.options.attributes) {

                var template = Handlebars.compile(HTMLInfoPopup);
                var html = template(layer.options);
                var popup = L.popup({ closeOnClick: true })
                    .setLatLng(latlng)
                    .setContent(html)
                    .openOn(this.map);
            }
        },
        updateModeView: function () {
            if (this.bbView) {
                this.bbView.updateMode(this.mode);
            }
        },

        showLayerPopup: function (layer, latlng) {
            // TO DO: en vez mostrar de una el contenido del shape en el sidebar, puedo
            // preguntar algo antes o usar un contextmenu


            if (layer.options.entityId) {
                this.giView.showShapeData(layer);
                /*
                var geoType = (layer instanceof L.Marker ? 1 : 2);
                var dataType = layer.options.className;
                var distance = 0;
                if (geoType == 2)
                    distance = this.mapViewUtils.getDistanceInMeters(layer.getLatLngs());

                this.getAndShowCases(layer.options.entityId, geoType, dataType, distance, latlng);
                */
            }
            else {
                showMessage("info", translate("save_changes_then_put_info"));
            }
        },
        updateShapeContent: function () {
            //this.getLayerByEntityId(this.giView.currentShape._leaflet_id);
            switch (this.giView.contentMode) {
                case "text":
                    var shape = this.giView.currentShape;

                    shape.options.isDirty = true;
                    shape.options.attrObj.text.value = this.giView.$infobar.find(".shapeinfo-content .summernote").code();
                    
                    var aux = $.grep(shape.options.attributes, function (e) {
                        return e.key === "text";
                    })[0];
                    if (aux) {
                        aux.value = shape.options.attrObj.text.value;
                    } else {
                        shape.options.attributes.push({
                            "key": "text",
                            "type": "html",
                            "value": shape.options.attrObj.text.value
                        })
                    }
                    shape.unbindPopup();
                    shape.bindPopup(shape.options.attrObj.text.value);
                    //if (shape.getPopup()) {
                    //    shape.setPopupContent(shape.options.attrObj.text.value);
                    //} else {
                    //}

                    showMessage("info", translate("content_applied_remember_to_save_project"));
                    //this.refreshTextAttribute();
                    break;
            }
        },

        getAndShowCases: function (entityId, geoType, dataType, distance, latlng) {
            // TO DO: 
            // Esta funcion arma el menu de popup que sale de cada shape
            if (!latlng) {
                var layer = this.getLayerByEntityId(entityId, geoType == "1" ? "node" : "link");
                if (layer) {
                    if (layer instanceof L.Polyline) {
                        latlng = layer.getLatLngs()[Math.floor(layer.getLatLngs().length / 2)];
                    }
                    else {
                        latlng = layer.getLatLng()
                    }
                    this.map.panTo(latlng, { animate: false });
                }
            }

            var that = this;
            var fpModel = new FPCaseModel();
            fpModel.getCasesFor(entityId, geoType, function (cases) {

                var menuItems = [];
                if (cases.length == 0) {
                    menuItems.push({
                        text: translate('add_base_case'),
                        iconCls: 'icon-plus',
                        callback: function () {
                            that.openForm(entityId, geoType, dataType, distance, -1);
                        }
                    });
                }
                else {
                    $.each(cases, function (ii, item) {
                        menuItems.push({
                            text: item.isBaseCase ? translate('edit_base_case') : item.name,
                            iconCls: item.isBaseCase ? 'icon-pencil' : 'icon-inbox',
                            callback: function () {
                                that.openForm(entityId, geoType, dataType, distance, item.idCaseByLink || item.idCaseByNode);
                            }
                        });
                    });

                    menuItems.push({
                        text: translate('create_new_fpProject'),
                        iconCls: 'icon-plus',
                        callback: function () {
                            that.openForm(entityId, geoType, dataType, distance, -1);
                        }
                    });

                }

                that.map.contextmenu.removeAllItems();
                $.each(menuItems, function (ii, itemMenu) {
                    that.map.contextmenu.addItem(itemMenu);
                });
                that.map.contextmenu.showAt(latlng);

            });
        },
        // generate geoData form show link and nodes clicked on corridor network
        generateTempGeoData: function (layer) {
            // TO DO: actualizar esta funcion
            var obj = {
                leaflet_id: layer._leaflet_id,
                link: {
                    entityId: layer.options.entityId,
                    name: layer.options.title || ""
                },
                linkColor: __mapColors[layer.options.className] || "#dd0000"
            };

            var that = this;
            var locateNode = function (latlng) {
                var node = {};
                var tolerance = 100;

                that.workLayer.eachLayer(function (e) {

                    var _layer = e;
                    var isMarker = _layer instanceof L.Marker;
                    if (isMarker) {
                        if (latlng.distanceTo(_layer.getLatLng()) < tolerance) {
                            node.leaflet_id = _layer._leaflet_id;
                            node.entityId = _layer.options.entityId;
                            node.dataType = _layer.options.className;
                            node.name = _layer.options.title;
                            node.img = 'img/map/pins/' + __mapImages[node.dataType];
                        }
                    }
                });

                return node;
            };

            obj.nodeFrom = locateNode(layer.getLatLngs()[0]);
            obj.nodeTo = locateNode(layer.getLatLngs()[layer.getLatLngs().length - 1]);

            if (obj.link.name == "" || obj.link.name.indexOf(" - ") >= 0) {
                var linkName = "";
                if (obj.nodeFrom)
                    linkName = obj.nodeFrom.name + " - ";
                if (obj.nodeTo)
                    linkName = linkName + obj.nodeTo.name;
                if (linkName != "")
                    obj.link.name = linkName;
            }

            return obj;
        },
        openForm: function (entityId, geoType, dataType, distance, caseId) {
            this.currentOpenFormData = {
                entityId: entityId,
                geoType: geoType
            };
            $("#projectMapSidebar").trigger("showLinksAndNodeForm", [entityId, geoType, dataType, distance, caseId]);
        },
        /* // comentado el evento
        markWithData: function (data) {
            this.currentLayersWithData = data;
            this.giView.markWithData(data);
        },
        */
        refreshLayerNameFromForm: function (name) {
            // To Do: ver para que sirve y actualizar
            if (name && this.currentOpenFormData) {

                if (this.currentOpenFormData.geoType == 1) {  //node
                    var leafletid = this.getLayerByEntityId(this.currentOpenFormData.entityId, this.currentOpenFormData.geoType == 1 ? "node" : "link")._leaflet_id;
                    this.addShapeName(leafletid, name);
                }
                else { // link
                    var link = this.getLayerByEntityId(this.currentOpenFormData.entityId, this.currentOpenFormData.geoType == 1 ? "node" : "link");
                    var tempGeoData = this.generateTempGeoData(link);
                    tempGeoData.link.name = name;
                    this.giView.updateSelectedLayer(tempGeoData);
                }

                this.currentOpenFormData = undefined;
            }
        },
        // show menu for change node type
        showMenuForChangeType: function (layer, latlang) {
            this.selectedObjectToAdd = layer;
            var that = this;
            this.map.contextmenu.removeAllItems();

            if (layer instanceof L.Marker) {
                $.each(this.extraContextMenuItems, function (ii, item) {
                    that.map.contextmenu.addItem(item);
                });
            }
            else {
                $.each(this.shapesContextMenuItems, function (ii, item) {
                    that.map.contextmenu.addItem(item);
                });
            }

            this.map.contextmenu.showAt(latlang);
        },
        // perform change layer type
        changeLayerType: function (className) {

            if (this.selectedObjectToAdd) {

                this.selectedObjectToAdd.options.isDirty = true;
                this.selectedObjectToAdd.options.className = className;
                this.changeModeOn();

                if (this.selectedObjectToAdd instanceof L.Marker) {

                    var icon = this.mapImages[className];
                    this.selectedObjectToAdd.setIcon(L.icon({
                        iconUrl: 'img/map/pins/' + icon,
                        iconSize: [32, 37],
                        iconAnchor: [16, 37]
                    }));

                    //update giview
                    this.updateGIViewFromMarker(this.selectedObjectToAdd);

                } else {
                    var newOptions = this.getShapeOptionsByType(className);

                    this.selectedObjectToAdd.setStyle({
                        color: newOptions.shapeOptions.color
                    });
                    this.selectedObjectToAdd.options.className = newOptions.shapeOptions.className;

                    this.giView.updateSelectedLayer(this.generateTempGeoData(this.selectedObjectToAdd));

                }

                this.selectedObjectToAdd = null;
            }
        },
        showHideMarkerLabels: function () {
            var show = this.tools_showLabels;
            this.workLayer.eachLayer(function (layer) {
                if (layer instanceof L.Marker) {
                    if (show)
                        layer.showLabel();
                    else
                        layer.hideLabel();
                }
            });
        },
        checkPersistMode: function () {
            if (!this.persistMode) {
                this.mapSetMode("free");
                this.updateModeView();
            }
        },
        checkRemoveLinkOfMarker: function (layer) {
            var that = this;
            this.workLayer.eachLayer(function (eachLayer) {
                if (eachLayer instanceof L.Polyline) {
                    if (layer.getLatLng().distanceTo(eachLayer.getLatLngs()[0]) < 100 ||
                            layer.getLatLng().distanceTo(eachLayer.getLatLngs()[eachLayer.getLatLngs().length - 1]) < 100) {

                        that.giView.removeLayerFromMap(eachLayer._leaflet_id);
                    }
                }
            });

        },
        showLayerByType: function (geoType, dataType) {
            var ids = [];
            var pos = [];
            this.workLayer.eachLayer(function (layer) {
                if ((layer instanceof L.Polyline && geoType == "link" || layer instanceof L.Marker && geoType == "node") && layer.options.className == dataType) {
                    ids.push(layer._leaflet_id)
                    if (geoType == "link") {
                        pos.push(layer.getLatLngs()[0]);
                        pos.push(layer.getLatLngs()[layer.getLatLngs().length - 1]);
                    }
                    else
                        pos.push(layer.getLatLng());
                }
            });
            if (ids.length > 0) {
                // no fit bounds.. 
                //this.map.fitBounds(pos, { paddingTopLeft: [550, 0],maxZoom:5 });
                this.addLayersToAux(ids);
            }
        },
        errorInSave: function () {
            this.changeModeOn();
        }

    });
    return view;
});
